let collect = require("../model/collect");
let { Router } = require("express");
let router = new Router();
router.use(require("../middleware/auth.js"));

// 添加收藏
router.post("/", async (req, res) => {
  const userID = req.userInfo._id;
  // console.log(userid, "2222");
  const { goodsID } = req.body;
  let datas = await collect.create({ userID, goodsID });
  res.status(200).json({
    msg: "添加成功",
    datas,
  });
});

// 查询收藏列表
router.get("/", async (req, res) => {
  const userID = req.userInfo._id;
  const datas = await collect
    .find()
    .sort({ _id: -1 })
    .populate(["userID", "goodsID"]);
  res.status(200).json({
    msg: "查询成功",
    datas,
  });
});

// 根据用户id查询
router.get("/condition_id", async (req, res) => {
  const userID = req.userInfo._id;
  const datas = await collect
    .find({ userID })
    .sort({ _id: -1 })
    .populate(["userID", "goodsID"]);
  res.status(200).json({
    msg: "查询成功",
    datas,
  });
});

// 查询单条收藏数据
// 查询收藏列表
router.get("/one", async (req, res) => {
  const userID = req.userInfo._id;
  const { goodsID } = req.query;
  const datas = await collect.findOne({ userID, goodsID });
  console.log(goodsID);
  if (datas) {
    res.status(200).json({
      msg: "查询成功",
      state: true,
      datas,
    });
    return;
  }
  res.status(201).json({
    msg: "没有这条数据",
    state: false,
  });
});

// 删除收藏表的数据
router.delete("/", async (req, res) => {
  const userID = req.userInfo._id;
  const { goodsID } = req.query;
  console.log(goodsID);
  let datas = await collect.findOneAndDelete({ goodsID });
  res.status(200).json({
    msg: "删除成功",
    datas,
  });
});
module.exports = router;
